package com.control.back.halo.bookmark.controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.control.back.halo.basic.controller.BaseController;
import com.control.back.halo.basic.json.Result;
import com.control.back.halo.basic.log4j.Logger;
import com.control.back.halo.bookmark.entity.Mark;
import com.control.back.halo.bookmark.parse.Readability;
import com.control.back.halo.bookmark.service.IMarkService;

@Controller
@RequestMapping("/mark")
public class MarkConntroller extends BaseController {

    @Autowired
    private IMarkService  markService;

    private static Logger logger = Logger.getLogger(MarkConntroller.class);
    
    @RequestMapping(value = { "", "/index" }, method = RequestMethod.GET)
    public String index(Model model) throws ClassNotFoundException, IOException {
        return "redirect:/category/index";
    }

    @RequestMapping("/brower/uploadMarkFile")
    public @ResponseBody Result uploadMarkFile(HttpServletRequest request, MultipartFile file) {

        Result r = new Result();
        if (!file.isEmpty()) {
            try {
                boolean flag = markService.analysisBrowerMarkHtmlAndSave(file.getInputStream());
                r.setSuccess(flag);
            } catch (Exception e) {
                r = Result.error("analysis htm error ." + e.getMessage());
            }
        } else {
            r = Result.error("file is empty!");
        }
        return r;
    }

    @RequestMapping("/queryMarks.json")
    public @ResponseBody Result queryMarks(String categoryIds, String name, Pageable pageable) {
        Result r = null;
        try {
            Page<Mark> markPage = markService.findMarksBy(categoryIds, name, pageable);
            r = new Result(true, "success", markPage);
        } catch (Exception e) {
            logger.error("query marks error ,params:[categoryIds:%s,name:%s,pageable:{%s,%s}]", e, categoryIds, name, pageable.getPageNumber(), pageable.getPageSize());
            r = new Result(false, "success", new PageImpl<Mark>(new ArrayList<Mark>(), pageable, 0));
        }

        return r;
    }

    @RequestMapping("/viewArtr")
    public @ResponseBody Map<String, String> viewAr(String href) {
        try {
            URL url = new URL(href);
            Readability r = new Readability(url, 5000);

            Map<String, String> result = new HashMap<String, String>();
            result.put("title", r.getTitle());
            result.put("content", r.getArticleContent());
            return result;
        } catch (MalformedURLException e) {
            logger.error("MalformedURLException error ", e);
        } catch (IOException e) {
            logger.error("IOException error ", e);
        }
        return null;
    }

    @RequestMapping("/repeatMark")
    public String repeatMark(Model model) {
        model.addAttribute("repeatMarks", markService.findRepeatMark());
        return "/category/repeatMark";
    }

    @RequestMapping("/remove.json")
    public @ResponseBody Result remove(String mIds) {
        logger.debug("remove mark params [mIds:%s]", mIds);
        boolean flag = false;
        try {
            if (StringUtils.isNotBlank(mIds)) {
                String[] mIdArray = mIds.split(",");
                for (String mId : mIdArray) {
                    if (StringUtils.isNotBlank(mId)) {
                        markService.delete(Long.parseLong(mId));
                    }
                }
            }
            flag = true;
        } catch (Exception e) {
            logger.error("remove mark error ", e);
        }
        return new Result(flag, "merge", flag);
    }

    @RequestMapping("/moveMarkToCategory.json")
    public @ResponseBody Result moveMarkToCategory(Long id, Long categoryId) {
        try {
            markService.moveMarkToCategory(id, categoryId);
            return Result.success("move success");
        } catch (Exception e) {
            logger.error("move error,params [id:%s,categoryId:%s]", e, id, categoryId);
        }
        return Result.error("move error");
    }

}
